﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Web.UI.WebControls;
using System.Web;
using System.IO;
using System.Threading;
using System.Net;
using System.Collections;
using System.Data;

namespace MSL.Utility.IO
{
    /// <summary>
    /// 文件操作类
    /// </summary>
    public class DirFile
    {
        #region 构造函数
        private static DirFile _instance;
        private static readonly object _lock = new Object();
        /// <summary>
        /// 
        /// </summary>
        private DirFile()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        /// <summary>
        /// 
        /// </summary>
        ~DirFile()
        {
            Dispose();
        }

        #endregion

        #region 单一实例

        /// <summary>
        /// 返回唯一实例
        /// </summary>
        public static DirFile Instance
        {
            get
            {
                return GetInstance();
            }
        }
        /// <summary>
        /// 获得单一实例
        /// </summary>
        /// <returns></returns>
        private static DirFile GetInstance()
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new DirFile();
                    }
                }
            }
            return _instance;
        }
        #endregion

        #region IDisposable 成员
        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            //Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        #region 文件存在性
        /// <summary>
        /// 文件存在性
        /// </summary>
        /// <returns></returns>
        public bool FileExist(string fileFullName)
        {
            string filePath = fileFullName.Substring(0, fileFullName.LastIndexOf("/") + 1);
            string fileName = fileFullName.Remove(0, filePath.Length);
            string Fileparentpath = HttpContext.Current.Server.MapPath(filePath);
            return File.Exists(Fileparentpath + fileName);
        }
        #endregion

        #region 获得文件名
        /// <summary>
        /// 获得文件名
        /// </summary>
        /// <param name="webfilename"></param>
        /// <returns></returns>
        public string GetFileName(string webFileName)
        {
            try
            {
                int lastslash = webFileName.LastIndexOf('/');
                string fileName = webFileName.Substring(lastslash + 1);
                return fileName;
            }
            catch
            {
                return "";
            }
        }
        #endregion

        #region 文件备份

        /// <summary>
        /// 备份文件
        /// </summary>
        /// <param name="sourceFileName">源文件名</param>
        /// <param name="destFileName">目标文件名</param>
        /// <param name="overwrite">当目标文件存在时是否覆盖</param>
        /// <returns>操作是否成功</returns>
        public bool BackupFile(string sourceFileName, string destFileName, bool overwrite)
        {
            if (!System.IO.File.Exists(sourceFileName))
            {
                throw new FileNotFoundException(sourceFileName + "文件不存在！");
            }
            if (!overwrite && System.IO.File.Exists(destFileName))
            {
                return false;
            }
            try
            {
                System.IO.File.Copy(sourceFileName, destFileName, true);
                return true;
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 备份文件,当目标文件存在时覆盖
        /// </summary>
        /// <param name="sourceFileName">源文件名</param>
        /// <param name="destFileName">目标文件名</param>
        /// <returns>操作是否成功</returns>
        public bool BackupFile(string sourceFileName, string destFileName)
        {
            return BackupFile(sourceFileName, destFileName, true);
        }
        #endregion

        #region 文件恢复
        /// <summary>
        /// 恢复文件
        /// </summary>
        /// <param name="backupFileName">备份文件名</param>
        /// <param name="targetFileName">要恢复的文件名</param>
        /// <param name="backupTargetFileName">要恢复文件再次备份的名称,如果为null,则不再备份恢复文件</param>
        /// <returns>操作是否成功</returns>
        public bool RestoreFile(string backupFileName, string targetFileName, string backupTargetFileName)
        {
            try
            {
                if (!System.IO.File.Exists(backupFileName))
                {
                    throw new FileNotFoundException(backupFileName + "文件不存在！");
                }
                if (backupTargetFileName != null)
                {
                    if (!System.IO.File.Exists(targetFileName))
                    {
                        throw new FileNotFoundException(targetFileName + "文件不存在！无法备份此文件！");
                    }
                    else
                    {
                        System.IO.File.Copy(targetFileName, backupTargetFileName, true);
                    }
                }
                System.IO.File.Delete(targetFileName);
                System.IO.File.Copy(backupFileName, targetFileName);
            }
            catch (Exception e)
            {
                throw e;
            }
            return true;
        }

        public bool RestoreFile(string backupFileName, string targetFileName)
        {
            return RestoreFile(backupFileName, targetFileName, null);
        }
        #endregion

        #region 文件删除
        /// <summary>
        /// 文件删除
        /// </summary>
        /// <param name="parentPath">所在父级目录</param>
        /// <param name="filename">文件名</param>
        /// <returns></returns>
        public bool DeleteFile(string parentPath, string filename)
        {
            try
            {
                string filefullname = HttpContext.Current.Server.MapPath(parentPath) + filename;
                File.Delete(filefullname);
                return true;
            }
            catch
            {

                return false;
            }
        }
        /// <summary>
        /// 文件删除
        /// </summary>
        /// <param name="FileFullName">物理路径文件名</param>
        /// <returns></returns>
        public bool DeleteFile(string fileFullName)
        {
            FileInfo fi = new FileInfo(fileFullName);
            if (fi.Exists)
            {
                try
                {
                    fi.Delete();
                    return true;

                }
                catch
                {
                    return false;
                }
            }
            return true;
        }
        #endregion

        #region 取得文件后缀名
        /// <summary>
        /// 取后缀名
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>.gif|.html格式</returns>
        public string GetPostfixStr(string fileName)
        {
            int start = fileName.LastIndexOf(".");
            int length = fileName.Length;
            string postfix = fileName.Substring(start, length - start);
            return postfix;
        }
        #endregion

        #region 读文件
        /// <summary>
        /// 读文件（读取文本内容）
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <returns></returns>
        public string ReadFile(string path)
        {
            string s = "";
            if (!System.IO.File.Exists(path))
                s = "不存在相应的目录";
            else
            {
                StreamReader f2 = new StreamReader(path, System.Text.Encoding.GetEncoding("gb2312"));
                s = f2.ReadToEnd();
                f2.Close();
                f2.Dispose();
            }
            return s;
        }
        #endregion

        #region 追加文件
        /// <summary>
        /// 追加文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="strings">新追加的内容</param>
        public void FileAdd(string path, string strings)
        {
            using (StreamWriter sw = File.AppendText(path))
            {
                sw.Write(strings);
                sw.Flush();
            }
        }
        #endregion

        #region 拷贝文件
        /// <summary>
        /// 拷贝文件
        /// </summary>
        /// <param name="OrignFile">原始文件路径</param>
        /// <param name="NewFile">新文件路径</param>
        public void CopyFile(string orignFile, string newFile)
        {
            File.Copy(orignFile, newFile, true);
        }

        /// <summary>
        /// 指定文件夹下面的所有内容copy到目标文件夹下面（如果目标文件夹为只读属性就会报错）
        /// </summary>
        /// <param name="srcPath">原始路径</param>
        /// <param name="aimPath">目标文件夹</param>
        public void CopyDir(string srcPath, string aimPath)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加之
                if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                    aimPath += Path.DirectorySeparatorChar;
                // 判断目标目录是否存在如果不存在则新建之
                if (!Directory.Exists(aimPath))
                    Directory.CreateDirectory(aimPath);
                // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
                //如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
                //string[] fileList = Directory.GetFiles(srcPath);
                string[] fileList = Directory.GetFileSystemEntries(srcPath);
                //遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    //先当作目录处理如果存在这个目录就递归Copy该目录下面的文件

                    if (Directory.Exists(file))
                        CopyDir(file, aimPath + Path.GetFileName(file));
                    //否则直接Copy文件
                    else
                        File.Copy(file, aimPath + Path.GetFileName(file), true);
                }
            }
            catch (Exception ee)
            {
                throw new Exception(ee.ToString());
            }
        }

        #endregion

        #region 移动文件
        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="OrignFile">原始路径</param>
        /// <param name="NewFile">新路径</param>
        public void FileMove(string orignFile, string newFile)
        {
            File.Move(orignFile, newFile);
        }
        #endregion

        #region 写文件
        /// <summary>
        /// 写文件（当文件不存时，则创建文件，并追加文件）
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="Strings">文件内容</param>
        public void WriteFile(string path, string content)
        {
            if (!System.IO.File.Exists(path))
            {
                System.IO.FileStream f = System.IO.File.Create(path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(path, true, System.Text.Encoding.UTF8);
            f2.WriteLine(content);
            f2.Close();
            f2.Dispose();
        }
        #endregion

        # region 获取文件夹下文件信息（DataTable）

        /// <summary>
        /// 获取指定目录下的所有目录及其文件信息
        /// </summary>
        /// <param name="dir">文件夹</param>
        /// <param name="method">获取方式。</param>
        /// <returns>DataTable</returns>
        public DataTable GetDirectoryAllInfos(string dir, FsoMethod method)
        {
            DataTable dt;

            try
            {
                DirectoryInfo dInfo = new DirectoryInfo(dir);
                dt = GetDirectoryAllInfo(dInfo, method);
            }
            catch (Exception exc)
            {
                throw new Exception(exc.ToString());
            }

            return dt;
        }

        /// <summary>
        /// 获取指定目录下的所有目录及其文件信息
        /// </summary>
        /// <param name="d">实例化的目录</param>
        /// <param name="method">获取方式。1、仅获取文件夹结构  2、仅获取文件结构  3、同时获取文件和文件夹信息</param>
        /// <returns></returns>
        private DataTable GetDirectoryAllInfo(DirectoryInfo d, FsoMethod method)
        {
            DataTable dt = new DataTable();
            DataRow dr;

            dt.Columns.Add("name");			//名称
            dt.Columns.Add("rname");		//名称
            dt.Columns.Add("content_type");	//文件MIME类型，如果是文件夹则置空
            dt.Columns.Add("type");			//类型：1为文件夹，2为文件
            dt.Columns.Add("path");			//文件路径
            dt.Columns.Add("creatime");		//创建时间
            dt.Columns.Add("size");			//文件大小

            // 获取文件夹结构信息
            DirectoryInfo[] dirs = d.GetDirectories();
            foreach (DirectoryInfo dir in dirs)
            {
                if (method == FsoMethod.File)
                {
                    dt = CopyDT(dt, GetDirectoryAllInfo(dir, method));
                }
                else
                {
                    dr = dt.NewRow();

                    dr[0] = dir.Name;
                    dr[1] = dir.FullName;
                    dr[2] = "";
                    dr[3] = 1;
                    dr[4] = dir.FullName.Replace(dir.Name, "");
                    dr[5] = dir.CreationTime;
                    dr[6] = "";

                    dt.Rows.Add(dr);

                    dt = CopyDT(dt, GetDirectoryAllInfo(dir, method));
                }
            }

            // 获取文件结构信息
            if (method != FsoMethod.Folder)
            {
                FileInfo[] files = d.GetFiles();
                foreach (FileInfo file in files)
                {
                    dr = dt.NewRow();

                    dr[0] = file.Name;
                    dr[1] = file.FullName;
                    dr[2] = file.Extension.Replace(".", "");
                    dr[3] = 2;
                    dr[4] = file.DirectoryName + "\\";
                    dr[5] = file.CreationTime;
                    dr[6] = file.Length;

                    dt.Rows.Add(dr);
                }
            }

            return dt;
        }

        /// <summary>
        /// 将两个结构一样的 DataTable 组合成一个 DataTable
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="child"></param>
        /// <returns>DataTable</returns>
        public DataTable CopyDT(DataTable parent, DataTable child)
        {
            DataRow dr;
            for (int i = 0; i < child.Rows.Count; i++)
            {
                dr = parent.NewRow();
                for (int j = 0; j < parent.Columns.Count; j++)
                {
                    dr[j] = child.Rows[i][j];
                }
                parent.Rows.Add(dr);
            }

            return parent;
        }

        /// <summary>
        /// 获取指定目录的目录信息
        /// </summary>
        /// <param name="dir">指定目录</param>
        /// <param name="method">获取方式。1、仅获取文件夹结构  2、仅获取文件结构  3、同时获取文件和文件夹信息</param>
        /// <returns>返回 DataTable</returns>
        public DataTable GetDirectoryInfos(string dir, FsoMethod method)
        {
            DataTable dt = new DataTable();
            DataRow dr;

            dt.Columns.Add("name");//名称
            dt.Columns.Add("type");//类型：1为文件夹，2为文件
            dt.Columns.Add("size");//文件大小，如果是文件夹则置空
            dt.Columns.Add("content_type");//文件MIME类型，如果是文件夹则置空
            dt.Columns.Add("createTime");//创建时间
            dt.Columns.Add("lastWriteTime");//最后修改时间

            // 获取文件夹结构信息
            if (method != FsoMethod.File)
            {
                for (int i = 0; i < GetDirs(dir).Length; i++)
                {
                    dr = dt.NewRow();
                    DirectoryInfo d = new DirectoryInfo(GetDirs(dir)[i]);

                    dr[0] = d.Name;
                    dr[1] = 1;
                    dr[2] = "";
                    dr[3] = "";
                    dr[4] = d.CreationTime;
                    dr[5] = d.LastWriteTime;

                    dt.Rows.Add(dr);
                }
            }

            // 获取文件结构信息
            if (method != FsoMethod.Folder)
            {
                for (int i = 0; i < GetFiles(dir).Length; i++)
                {
                    dr = dt.NewRow();
                    FileInfo f = new FileInfo(GetFiles(dir)[i]);

                    dr[0] = f.Name;
                    dr[1] = 2;
                    dr[2] = f.Length;
                    dr[3] = f.Extension.Replace(".", "");
                    dr[4] = f.CreationTime;
                    dr[5] = f.LastWriteTime;

                    dt.Rows.Add(dr);
                }
            }

            return dt;
        }

        private String[] GetDirs(string dir)
        {
            return Directory.GetDirectories(dir);
        }

        private String[] GetFiles(string dir)
        {
            return Directory.GetFiles(dir);
        }

        # endregion

        #region 获取指定文件夹信息

        /// <summary>
        /// 获取指定文件夹的信息，如：文件夹大小，文件夹数，文件数
        /// </summary>
        /// <param name="dir">指定文件夹路径</param>
        /// <returns>返回 String</returns>
        public long[] GetDirInfos(string dir)
        {
            long[] intResult = new long[3];
            DirectoryInfo d = new DirectoryInfo(dir);
            intResult = DirInfo(d);

            return intResult;
        }

        private long[] DirInfo(DirectoryInfo d)
        {
            long[] intResult = new long[3];

            long Size = 0;
            long Dirs = 0;
            long Files = 0;
            // 计算文件大小
            FileInfo[] files = d.GetFiles();
            Files += files.Length;
            foreach (FileInfo file in files)
            {
                Size += file.Length;
            }
            // 计算文件夹
            DirectoryInfo[] dirs = d.GetDirectories();
            Dirs += dirs.Length;
            foreach (DirectoryInfo dir in dirs)
            {
                Size += DirInfo(dir)[0];
                Dirs += DirInfo(dir)[1];
                Files += DirInfo(dir)[2];
            }

            intResult[0] = Size;
            intResult[1] = Dirs;
            intResult[2] = Files;
            return intResult;
        }

        #endregion

        #region 获取指定文件夹下所有子目录及文件(树形)
        /// <summary>
        /// 获取指定文件夹下所有子目录及文件
        /// </summary>
        /// <param name="Path">详细路径</param>
        public string GetFoldAll(string path)
        {

            string str = "";
            DirectoryInfo thisOne = new DirectoryInfo(path);
            str = ListTreeShow(thisOne, 0, str);
            return str;
        }

        /// <summary>
        /// 获取指定文件夹下所有子目录及文件函数
        /// </summary>
        /// <param name="theDir">指定目录</param>
        /// <param name="nLevel">默认起始值,调用时,一般为0</param>
        /// <param name="Rn">用于迭加的传入值,一般为空</param>
        /// <returns></returns>
        public string ListTreeShow(DirectoryInfo theDir, int nLevel, string Rn)//递归目录 文件
        {
            DirectoryInfo[] subDirectories = theDir.GetDirectories();//获得目录
            foreach (DirectoryInfo dirinfo in subDirectories)
            {

                if (nLevel == 0)
                {
                    Rn += "├";
                }
                else
                {
                    string _s = "";
                    for (int i = 1; i <= nLevel; i++)
                    {
                        _s += "│&nbsp;";
                    }
                    Rn += _s + "├";
                }
                Rn += "<b>" + dirinfo.Name.ToString() + "</b><br />";
                FileInfo[] fileInfo = dirinfo.GetFiles();   //目录下的文件
                foreach (FileInfo fInfo in fileInfo)
                {
                    if (nLevel == 0)
                    {
                        Rn += "│&nbsp;├";
                    }
                    else
                    {
                        string _f = "";
                        for (int i = 1; i <= nLevel; i++)
                        {
                            _f += "│&nbsp;";
                        }
                        Rn += _f + "│&nbsp;├";
                    }
                    Rn += fInfo.Name.ToString() + " <br />";
                }
                Rn = ListTreeShow(dirinfo, nLevel + 1, Rn);


            }
            return Rn;
        }

        /// <summary>
        /// 获取指定文件夹下所有子目录及文件(下拉框形)
        /// </summary>
        /// <param name="Path">详细路径</param>
        ///<param name="DropName">下拉列表名称</param>
        ///<param name="tplPath">默认选择模板名称</param>
        public string GetFoldAll(string path, string dropName, string tplPath)
        {
            string strDrop = "<select name=\"" + dropName + "\" id=\"" + dropName + "\"><option value=\"\">--请选择详细模板--</option>";
            string str = "";
            DirectoryInfo thisOne = new DirectoryInfo(path);
            str = ListTreeShow(thisOne, 0, str, tplPath);
            return strDrop + str + "</select>";

        }

        /// <summary>
        /// 获取指定文件夹下所有子目录及文件函数(重载1)
        /// </summary>
        /// <param name="theDir">指定目录</param>
        /// <param name="nLevel">默认起始值,调用时,一般为0</param>
        /// <param name="Rn">用于迭加的传入值,一般为空</param>
        /// <param name="tplPath">默认选择模板名称</param>
        /// <returns></returns>
        public string ListTreeShow(DirectoryInfo theDir, int nLevel, string Rn, string tplPath)//递归目录 文件
        {
            DirectoryInfo[] subDirectories = theDir.GetDirectories();//获得目录

            foreach (DirectoryInfo dirinfo in subDirectories)
            {

                Rn += "<option value=\"" + dirinfo.Name.ToString() + "\"";
                if (tplPath.ToLower() == dirinfo.Name.ToString().ToLower())
                {
                    Rn += " selected ";
                }
                Rn += ">";

                if (nLevel == 0)
                {
                    Rn += "┣";
                }
                else
                {
                    string _s = "";
                    for (int i = 1; i <= nLevel; i++)
                    {
                        _s += "│&nbsp;";
                    }
                    Rn += _s + "┣";
                }
                Rn += "" + dirinfo.Name.ToString() + "</option>";


                FileInfo[] fileInfo = dirinfo.GetFiles();   //目录下的文件
                foreach (FileInfo fInfo in fileInfo)
                {
                    Rn += "<option value=\"" + dirinfo.Name.ToString() + "/" + fInfo.Name.ToString() + "\"";
                    if (tplPath.ToLower() == fInfo.Name.ToString().ToLower())
                    {
                        Rn += " selected ";
                    }
                    Rn += ">";

                    if (nLevel == 0)
                    {
                        Rn += "│&nbsp;├";
                    }
                    else
                    {
                        string _f = "";
                        for (int i = 1; i <= nLevel; i++)
                        {
                            _f += "│&nbsp;";
                        }
                        Rn += _f + "│&nbsp;├";
                    }
                    Rn += fInfo.Name.ToString() + "</option>";
                }
                Rn = ListTreeShow(dirinfo, nLevel + 1, Rn, tplPath);


            }
            return Rn;
        }
        #endregion

        #region 获取文件夹大小
        /// <summary>
        /// 获取文件夹大小
        /// </summary>
        /// <param name="dirPath">文件夹路径</param>
        /// <returns></returns>
        public long GetDirectoryLength(string dirPath)
        {
            if (!Directory.Exists(dirPath))
                return 0;
            long len = 0;
            DirectoryInfo di = new DirectoryInfo(dirPath);
            foreach (FileInfo fi in di.GetFiles())
            {
                len += fi.Length;
            }
            DirectoryInfo[] dis = di.GetDirectories();
            if (dis.Length > 0)
            {
                for (int i = 0; i < dis.Length; i++)
                {
                    len += GetDirectoryLength(dis[i].FullName);
                }
            }
            return len;
        }
        #endregion

        #region 获取指定文件详细属性
        /// <summary>
        /// 获取指定文件详细属性
        /// </summary>
        /// <param name="filePath">文件详细路径</param>
        /// <returns></returns>
        public string GetFileAttibe(string filePath)
        {
            string str = "";
            System.IO.FileInfo objFI = new System.IO.FileInfo(filePath);
            str += "详细路径:" + objFI.FullName + "<br>文件名称:" + objFI.Name + "<br>文件长度:" + objFI.Length.ToString() + "字节<br>创建时间" + objFI.CreationTime.ToString() + "<br>最后访问时间:" + objFI.LastAccessTime.ToString() + "<br>修改时间:" + objFI.LastWriteTime.ToString() + "<br>所在目录:" + objFI.DirectoryName + "<br>扩展名:" + objFI.Extension;
            return str;
        }
        #endregion

        #region 文件夹操作
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <param name="parentPath"></param>
        public void CreateFolder(string path, string parentPath)
        {
            DirectoryInfo di = new DirectoryInfo(parentPath);
            if (!di.Exists)
                di.CreateSubdirectory(path);
        }
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="path"></param>
        public void CreateFolder(string path)
        {
            DirectoryInfo di = new DirectoryInfo(path);
            if (!di.Exists)
            {
                di.Create();
            }
        }

        /// <summary>
        /// 递归删除文件夹及其下的所有文件
        /// Directory.Delete能否直接删除下面的所有文件未测试
        /// </summary>
        /// <param name="dir"></param>
        public void DeleteFolder(string dir)
        {
            if (Directory.Exists(dir)) //如果存在这个文件夹删除之 
            {
                foreach (string d in Directory.GetFileSystemEntries(dir))
                {
                    if (File.Exists(d))
                        File.Delete(d); //直接删除其中的文件                        
                    else
                        DeleteFolder(d); //递归删除子文件夹 
                }
                Directory.Delete(dir, true); //删除已空文件夹                 
            }
        }

        /// <summary>
        /// 移动文件夹
        /// </summary>
        public bool MoveFolder(string oldPath, string newPath)
        {
            try
            {
                Directory.Move(oldPath, newPath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 复制文件夹 
        /// 将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
        /// </summary>
        public bool CopyFolder(string source, string destination)
        {
            try
            {
                String[] files;
                if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) destination += Path.DirectorySeparatorChar;
                if (!Directory.Exists(destination)) Directory.CreateDirectory(destination);
                files = Directory.GetFileSystemEntries(source);
                foreach (string element in files)
                {
                    if (Directory.Exists(element))
                        CopyFolder(element, destination + Path.GetFileName(element));
                    else
                        File.Copy(element, destination + Path.GetFileName(element), true);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region 检测文件安全性
        /// <summary>
        /// 判断是否为安全文件名
        /// </summary>
        /// <param name="str">文件名</param>
        public bool IsSafeName(string strExtension)
        {
            strExtension = strExtension.ToLower();
            if (strExtension.LastIndexOf(".") >= 0)
            {
                strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
            }
            else
            {
                strExtension = ".txt";
            }
            string[] arrExtension = { ".htm", ".html", ".txt", ".js", ".css", ".xml", ".sitemap", ".jpg", ".gif", ".png", ".rar", ".zip" };
            for (int i = 0; i < arrExtension.Length; i++)
            {
                if (strExtension.Equals(arrExtension[i]))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        ///  判断是否为不安全文件名
        /// </summary>
        /// <param name="str">文件名、文件夹名</param>
        public bool IsUnsafeName(string strExtension)
        {
            strExtension = strExtension.ToLower();
            if (strExtension.LastIndexOf(".") >= 0)
            {
                strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
            }
            else
            {
                strExtension = ".txt";
            }
            string[] arrExtension = { ".", ".asp", ".aspx", ".cs", ".net", ".dll", ".config", ".ascx", ".master", ".asmx", ".asax", ".cd", ".browser", ".rpt", ".ashx", ".xsd", ".mdf", ".resx", ".xsd" };
            for (int i = 0; i < arrExtension.Length; i++)
            {
                if (strExtension.Equals(arrExtension[i]))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        ///  判断是否为可编辑文件
        /// </summary>
        /// <param name="str">文件名、文件夹名</param>
        public bool IsCanEdit(string strExtension)
        {
            strExtension = strExtension.ToLower();

            if (strExtension.LastIndexOf(".") >= 0)
            {
                strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
            }
            else
            {
                strExtension = ".txt";
            }
            string[] arrExtension = { ".htm", ".html", ".txt", ".js", ".css", ".xml", ".sitemap" };
            for (int i = 0; i < arrExtension.Length; i++)
            {
                if (strExtension.Equals(arrExtension[i]))
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region 删除x天前的文件

        /// <summary>
        /// 删除x天前的文件  
        /// </summary>
        /// <param name="path"></param>
        /// <param name="extenArray"></param>
        /// <param name="days"></param>
        public void DeleteFiles(string path, string[] extenArray, int days)
        {
            if (path == "")
            {
                return;
            }
            List<string> files = GetAllFiles(path, extenArray);
            foreach (string p in files)
            {
                FileInfo f = new FileInfo(path + p);
                if (f.Exists && f.CreationTime < DateTime.Now.AddDays(-(days)))
                {
                    try
                    {
                        f.Delete();
                    }
                    catch
                    {
                        //Response.Write("<script>alert('删除出错！');                }
                    }
                }
            }
        }
        #endregion

        #region 获取指定目录和扩展名的所有文件

        /// <summary> 
        /// 获取指定目录和扩展名的所有文件
        /// </summary>
        /// <param name="path">绝对路径</param>
        /// <param name="extenArray">文件后缀数组</param>
        /// <returns></returns>
        public List<string> GetAllFiles(string path, string[] extenArray)
        {
            List<string> liAddr = new List<string>();//临时存放路径的链表
            if (Directory.Exists(path))
            {
                string[] fileList = Directory.GetFileSystemEntries(path);
                liAddr.Clear();
                foreach (string file in fileList)
                {
                    string newStr = Path.GetFullPath(file);
                    string filename = Path.GetFileName(file);
                    string strExtension = Path.GetExtension(newStr).ToLower();
                    if (extenArray == null || extenArray.Length == 0)
                    {
                        liAddr.Add(filename);
                        continue;
                    }
                    foreach (string ss in extenArray)
                    {
                        if (string.Equals(strExtension, ss, StringComparison.CurrentCultureIgnoreCase) || string.Equals(strExtension, "." + ss, StringComparison.CurrentCultureIgnoreCase))
                        {
                            liAddr.Add(filename);
                        }
                    }
                }
            }
            return liAddr;
        }
        #endregion

        #region 检测文件是否被占用
        /// <summary>
        /// 检测文件是否被其它进程占用 马山林 2014-01-28 添加
        /// </summary>
        /// <param name="sourePath">文件详细路径</param>
        /// <returns></returns>
        public static bool ChkFileOccupation(string sourePath)
        {
            bool result = false;
            try
            {
                File.Move(sourePath, sourePath);
            }
            catch (Exception)
            {
                result = true;
            }
            return result;
        }
        #endregion

        #region 重命名文件
        /// <summary>
        /// 重命名文件
        /// </summary>
        /// <param name="sourePath">源地址</param>
        /// <param name="newFileName">新文件名</param>
        /// <returns></returns>
        private static bool RenameFile(string sourePath, string newFileName)
        {
            bool isSuccess = false;
            string path = sourePath.Remove(sourePath.LastIndexOf("\\"));
            if (!sourePath.Equals(path + newFileName))//相同
            {
                try
                {
                    //复制文件
                    File.Move(sourePath, path + newFileName);
                    isSuccess = true;
                }
                catch (Exception e)
                {
                }
            }
            return isSuccess;
        }
        #endregion
    }
    /// <summary>
    /// 文件系统的处理对象
    /// </summary>
    public enum FsoMethod
    {
        /// <summary>
        /// 仅用于处理文件夹
        /// </summary>
        Folder = 0,
        /// <summary>
        /// 仅用于处理文件
        /// </summary>
        File,
        /// <summary>
        /// 文件和文件夹都参与处理
        /// </summary>
        All
    }
}
